package com.tn.controller.producer;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gitee.hifong45.Kv;
import com.tn.controller.alarm.common.constants.Constants;
import com.tn.controller.alarm.common.model.InputVO;
import com.tn.controller.alarm.common.model.OutputVO;
import com.tn.controller.alarm.common.model.external.subsystem.vo.ExitPermitVO;
import com.tn.dao.external.subsystem.IGateTruckDao;
import com.tn.service.cardrobot.impl.CardSendRobotServiceImpl;
import com.tn.service.external.subsystem.GateRestfulService;
import com.tn.socket.CardSendRobot;
import com.tn.socket.SocketPoolRunner;
import com.tn.utils.CheckParamUtil;
import com.tn.utils.JsonUtil;
import com.tn.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;

/**
 * @ClassName GateRestful
 * @Description TODO
 * @Author Yezhongzhu
 * @Date 2021/12/3 14:07
 * @Version v1.0
 **/
@RestController
@RequestMapping("/aucy/")
@Slf4j
public class GateRestful {
    @Autowired
    private GateRestfulService service;

    @Autowired
    private IGateTruckDao iGateDao;

    @Resource
    private WebSocket webSocket;

    @Resource
    private CardSendRobotServiceImpl cardSendRobotServiceImpl;

    /**
     * 接收车牌信息判断闸口是否抬杆
     * @param
     * @return
     */
    // {"orgId":"HSXG1523839327000","ts":1523839327000,"md":"f5750c9a1d040282abbccb7840643c69","data":{"license":"豫QC7667","machineid":"12345_1","picture":"aaxx","machineType":0,"gateType":1}}
    @RequestMapping(value ="acceptTruckData",
            consumes={"application/json;charset=utf-8",
                    "application/x-www-form-urlencoded;charset=utf-8",
                    "application/x-www-form-urlencoded;charset=GB2312"},
            produces = "application/json;charset=utf-8")
    public String acceptTruckData(@RequestBody InputVO<ExitPermitVO> inputVO) throws ParseException {
        OutputVO<ExitPermitVO> outputVO = new OutputVO<>();
        if(!CheckParamUtil.checkGateParam(inputVO)||StringUtils.isBlank(inputVO.getData().getPicture())
        ||null==inputVO.getData().getMachineType()||StringUtils.isBlank(inputVO.getData().getMachineId())){
            outputVO.setInfo(Constants.OtherSys.STATUS.PARAM.getMessage());
            outputVO.setStatus(Constants.OtherSys.STATUS.PARAM.getCode());
            return JSON.toJSONString(outputVO);
        }

        ExitPermitVO vo = inputVO.getData();
        String gateId = getGateId(vo.getMachineId());
        if("003".equals(gateId)||"004".equals(gateId)){
            vo.setPermitThroughType(Constants.PERMIT_THROUGH_STOP_OUT);
            outputVO.setData(vo);
            return JSON.toJSONString(outputVO);
        }

        boolean flag = service.checkIfTruckPassGate(vo);
        String stationId=null;
        String usable=null;
        Kv carMachineInfo = cardSendRobotServiceImpl.getCarMachineInfo(stationId, StrUtil.isBlank(usable));
        webSocket.sendOneMessage("hs02",JsonUtil.obj2String(carMachineInfo));
        if(flag){
            vo.setPermitThroughType(Constants.PERMIT_THROUGH_OUT);
        }else{
            vo.setPermitThroughType(Constants.PERMIT_THROUGH_STOP_OUT);
        }
        outputVO.setData(vo);
        return JSON.toJSONString(outputVO);
    }

    private String getGateId(String machineId) {
        // 大门闸口规则：大门号_闸道号 如：一号大门1号闸道,值：001_1
        String[] index = StringUtils.split(machineId, "_");
        return index[0];
    }
    /**
     * 接收车牌通过信息
     * @param body
     * @return
     */
    @RequestMapping(value = "acceptTruckPermitThroughData",
            consumes={"application/json;charset=utf-8",
            "application/x-www-form-urlencoded;charset=utf-8",
            "application/x-www-form-urlencoded;charset=GB2312"},
            produces = "application/json;charset=utf-8")
    public String acceptTruckPermitThroughData(@RequestBody String body) {
        InputVO<ExitPermitVO> inputVO = JSON.parseObject(body,new TypeReference<InputVO<ExitPermitVO>> (){});
        OutputVO outputVO = new OutputVO();
        if (!CheckParamUtil.checkGateParam(inputVO)) {
            outputVO.setInfo(Constants.OtherSys.STATUS.PARAM.getMessage());
            outputVO.setStatus(Constants.OtherSys.STATUS.PARAM.getCode());
            return JSON.toJSONString(outputVO);
        }

        service.addTruckGateData(inputVO.getData()); // 添加货车通过闸口的相关信息
        return JSON.toJSONString(outputVO);
    }


    @Autowired
    private SocketPoolRunner socketPoolRunner;

    @RequestMapping("check")
    public OutputVO check() {
        return new OutputVO();
    }

    @RequestMapping("socketSend")
    public OutputVO socketSend(String ip,String msg) {
        for (int i = 0; i < socketPoolRunner.clients.size(); i++) {
            CardSendRobot serverAcceptMessage = socketPoolRunner.clients.get(i);
            if(StringUtils.isNotBlank(ip)&&ip.equals(serverAcceptMessage.getHostAddress())){
                serverAcceptMessage.send(msg);
            }
        }
        return new OutputVO();
    }
}
